import json

from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import JsonResponse
from django.shortcuts import render
from django.views import View

from houses.models import House
from orders.models import Order


class AddOrderView(View):
    def get(self, request):
        """添加订单"""

        # 获取用户
        user = request.user
        if not user.is_authenticated:
            return JsonResponse({
                'errno': 4101,
                'errmsg': '请登录'
            })

        # 获取数据
        recv_data = json.loads(request.body)
        house_id = recv_data.get('house_id')
        start_date = recv_data.get('start_date')
        end_date = recv_data.get('end_date')

        # 校验数据
        if not all([house_id, start_date, end_date]):
            return JsonResponse({
                'errno': 9999,
                'errmsg': '参数不全'
            })

        try:
            house = House.objects.get(id=house_id)
        except:
            return JsonResponse({
                'errno': 9999,
                'errmsg': '房源不存在'
            })

        import datetime
        start_date = datetime.datetime.strptime(start_date, '%Y-%m-%d').date()
        end_date = datetime.datetime.strptime(end_date, '%Y-%m-%d').date()
        daysdelta = (end_date - start_date).days

        if (house.min_days > daysdelta) or (house.max_days < daysdelta and house.max_days != 0):
            return JsonResponse({'errno': 9999, 'errmsg': '时间不匹配'})

        # 校验该日期是否已被预定
        orders = house.order_set.filter(status__in=(1, 2, 3, 4))
        for order in orders:
            if order.begin_date >=end_date and order.end_date <= start_date:
                pass
            else:
                return JsonResponse({'errno': 9999, 'errmsg': '该日期已被预定'})

        # 创建订单
        house.order_count += 1
        house.save()

        order = Order.objects.create(
            user=user,
            house=house,
            begin_date=start_date,
            end_date=end_date,
            days=daysdelta,
            house_price=house.price,
            amount=house.price * daysdelta
        )

        return JsonResponse({
            'data': {
                'order_id': order.id
            },
            'errmsg': '下单成功',
            'errno': 0
        })


class OrderListView(LoginRequiredMixin, View):
    def get(self, request):
        """获取订单列表"""

        # 获取数据
        user = request.user
        role = request.GET.get('role')

        if role == 'custom':  # 获取房客订单
            orders = user.orders.all()
            order_list = []
            for order in orders:
                order_data = {
                    "amount": order.amount,
                    "comment": order.comment,
                    "ctime": order.create_time,
                    "days": order.days,
                    "end_date": order.end_date,
                    "img_url": order.house.index_image_url,
                    "order_id": order.id,
                    "start_date": order.begin_date,
                    "status": order.status,
                    "title": order.house.title
                }
                order_list.append(order_data)

            res = {
                'data': {
                    'orders': order_list
                },
                'errmsg': 'OK',
                'errno': 0
            }
            return JsonResponse(res)

        elif role == 'landlord':  # 获取房东订单
            houses = user.houses.all()

            order_list = []
            for house in houses:
                orders = house.order_set.all()
                for order in orders:
                    order_data = {
                        "amount": order.amount,
                        "comment": order.comment,
                        "ctime": order.create_time,
                        "days": order.days,
                        "end_date": order.end_date,
                        "img_url": house.index_image_url,
                        "order_id": order.id,
                        "start_date": order.begin_date,
                        "status": order.status,
                        "title": house.title
                    }
                    order_list.append(order_data)

            res = {
                'data': {
                    'orders': order_list
                },
                'errmsg': 'OK',
                'errno': 0
            }
            return JsonResponse(res)

        else:
            return JsonResponse({'errno': 9999, 'errmsg': '参数有误'})


class OrderOperationView(LoginRequiredMixin, View):

    def put(self, request, order_id):
        """接单或拒单"""

        # 获取数据
        user = request.user
        action = json.loads(request.body).get('action')
        reason = json.loads(request.body).get('reason')

        # 校验数据
        if (not action) or (action == 'reject' and (not reason)):
            return JsonResponse({
                'errno': 9999,
                'errmsg': '参数不全'
            })

        try:
            order = Order.objects.get(id=order_id)
        except:
            return JsonResponse({
                'errno': 9999,
                'errmsg': '订单不存在'
            })

        # 处理订单
        if action == 'reject':  # 拒单
            order.status = 1
            order.save()

            return JsonResponse({
                'errno': 0,
                'errmsg': '操作成功'
            })

        elif action == 'accept':  # 接单
            order.status = 6
            order.comment = reason
            order.save()

            return JsonResponse({
                'errno': 0,
                'errmsg': '操作成功'
            })

        else:
            return JsonResponse({
                'errno': 9999,
                'errmsg': '参数错误'
            })


class OrderCommentView(LoginRequiredMixin, View):
    def put(self, request, order_id):
        """订单评价"""

        comment = json.loads(request.body).get('comment')
        if not comment:
            return JsonResponse({'errno': 9999, 'errmsg': '参数不全'})

        try:
            order = Order.objects.get(id=order_id)
            if order not in request.user.orders.all():
                return JsonResponse({'errno': 9999, 'errmsg': '订单错误'})
        except:
            return JsonResponse({
                'errno': 9999,
                'errmsg': '订单不存在'
            })

        order.comment = comment
        order.status = 4
        order.save()

        return JsonResponse({
            'errno': 0,
            'errmsg': '评论成功'
        })

